<?php

class InitController extends AppController
{
	var $name = 'Init';
	var $helpers = array('Html', 'Form');
	var $uses = array('User', 'Config', 'Account', 'Tariff', 'Transaction');

	function init()
	{
		$this->Access('guest');

		$model = $this->User->name;
		$this->set('formName', $model);
		$this->pageTitle = __d('init', 'init_title', true);
		$list = $this->{$model}->generateList(null, 'id');

		if (empty($list)) {
			if (!empty($this->data[$model])) {
				$this->data[$model]['username'] = $this->Config->getDefaultAdminLogin();
				$this->data[$model]['status'] = 'ACTIVE';
				$this->data[$model]['role'] = 'ADMIN';

				$error_msg = '';
				if ($this->{$model}->save($this->data)) {

    			} elseif (!empty($this->{$model}->validationErrors)) {
    				$error_msg = __d(null, 'Data are incorrectly entered.', true).' '.__d(null, 'Try again.', true);
    			} else {
        		    $error_msg = __d(null, 'There was an internal error.', true).' '.__d(null, 'Try later.', true);
    			}
    			if (empty($error_msg)) {
					$data_accounts = array();
					$accounts_model = $this->Account->name;
					$temp_accounts = $this->Config->getCommissionAccountsNumbers();
					foreach ($temp_accounts as $acnt_key => $acnt_val) {
						$currencies = $this->Config->getCurrencies();
						foreach ($currencies as $cur_val){
							$data_accounts[$accounts_model]['currency'] = $cur_val;
							$data_accounts[$accounts_model]['status'] = 'ACTIVE';
							$data_accounts[$accounts_model]['number'] = $acnt_val;
							$data_accounts[$accounts_model]['type'] = $acnt_key;

							$this->{$accounts_model}->create($data_accounts);
							$this->{$accounts_model}->save($data_accounts);
						}
					}

					$data_tariffs = array();
					$tariffs_model = $this->Tariff->name;
					$operation_types = $this->Transaction->getOperationTypes();
					$operation_types = array_combine($operation_types, $operation_types);
					$shift = '5 seconds';
					$date = date('Y-m-d H:i:s', time() + $shift);
					if(isset($operation_types['INNER']))
						unset($operation_types['INNER']);

					foreach ($operation_types as $oper_type) {
						$data_tariffs[$tariffs_model]['data'] = '0%';
						$data_tariffs[$tariffs_model]['status'] = 'ACTIVE';
						$data_tariffs[$tariffs_model]['type'] = $oper_type;
						$data_tariffs[$tariffs_model]['start_date'] = $date;

						$this->{$tariffs_model}->create($data_tariffs);
						$this->{$tariffs_model}->save($data_tariffs);
					}

					$this->Auth->login('user', $this->{$model}->getInsertID(), $this->data[$model]['username'], '/profile/');
					exit();
    			} else {
    			    $this->msgError($error_msg, @$error_code);
    			}
				$this->data[$model]['password'] = '';
				$this->data[$model]['confirm_password'] = '';
			} else {
                $this->data[$model]['username'] = $this->Config->getDefaultAdminLogin();
			}
		} else {
			$this->redirect('/login');
			exit();
		}
	}

}

?>